package com.pipayshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.pipayshop.domain.ShopCategory;
import com.pipayshop.domain.vo.ShopCategoryVO;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.mapper.OnlineStoreShopCategoryMapper;
import com.pipayshop.service.OnlineStoreShopCategoryService;
import com.pipayshop.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaoqiu
 * @date 2024/9/9 15:14
 * @description
 */
@Service
@Slf4j
public class OnlineStoreShopCategoryServiceImpl extends ServiceImpl<OnlineStoreShopCategoryMapper, ShopCategory> implements OnlineStoreShopCategoryService {

    @Autowired
    private OnlineStoreShopCategoryMapper onlineStoreShopCategoryMapper;


    @Override
    @Cacheable(value = Constants.CATEGORY_LIST_KEY ,key = "#categoryPid")
    public List<ShopCategory> getList(Long categoryPid) {
        //1.根据分类Pid获取分类集合
//        List<ShopCategory> categories = onlineStoreShopCategoryMapper.selectList(new LambdaQueryWrapper<ShopCategory>()
//                .eq(ShopCategory::getCategoryPid, categoryPid)
//                .eq(ShopCategory::getDelFlag, 0)  //0代表为删除
//        );
        List<ShopCategory> categories = onlineStoreShopCategoryMapper.selectLists(categoryPid);

        return categories.size() != 0 ? categories : new ArrayList<>();
    }

    @Override
    public List<ShopCategory> selectAll() {
        return onlineStoreShopCategoryMapper.selectAll();
    }

    @Override
    public List<ShopCategoryVO> selectList() {
        return onlineStoreShopCategoryMapper.selectGetList();
    }

    @Override
    public String insertAndupdate(ShopCategory category) {
        // 根据分类 ID 查询分类信息
        ShopCategory shopCategory = onlineStoreShopCategoryMapper.selectById(category.getCategoryId());

        // 如果分类不存在，直接添加新数据
        if (shopCategory == null) {
            onlineStoreShopCategoryMapper.insert(category);
            return "添加数据成功";
        }

        // 如果分类存在，根据 delFlag 更新状态
        if (category.getDelFlag() == 1) {
            shopCategory.setDelFlag(1); // 将 delFlag 更新为 1
        } else if (category.getDelFlag() == 0) {
            shopCategory.setDelFlag(0); // 将 delFlag 更新为 0
        } else {
            return "无效的 delFlag 值，操作失败";
        }

        // 更新分类信息
        onlineStoreShopCategoryMapper.updateById(shopCategory);

        // 返回操作结果
        return category.getDelFlag() == 1 ? "分类禁用成功" : "分类启动成功";
    }


}
